package models

import (
	"errors"
	"github.com/astaxie/beego/orm"
	"object/go_cms/valid"
	"strconv"
)

type GroupModels struct {
}

type Group struct {
	Id         int    `orm:pk;auto`
	Group_name string `orm:size(50);default("")`
	Status     int    `orm:size(1)`
}

func init() {
	orm.RegisterModel(new(Group))
}

// 获取
func (m *GroupModels) Get(id int) (Group, error) {
	group := Group{Id: id}
	o := orm.NewOrm()
	err := o.Read(&group)
	return group, err
}

// 列表
func (m *GroupModels) Query() ([]Group, error) {
	var list []Group
	ps := getQueryTable("group")
	_, err := ps.All(&list)
	return list, err
}

//添加
func (m *GroupModels) Add(param map[string]interface{}) (int64, error) {
	g := valid.GroupValid{}
	b, err := g.ValidAdd(param)
	if !b {
		return 0, errors.New(err)
	}
	group := Group{}
	group.Group_name = param["group_name"].(string)
	o := orm.NewOrm()
	return o.Insert(&group)
}

//修改
func (m *GroupModels) Edit(param map[string]interface{}) (int64, error) {
	g := valid.GroupValid{}
	b, err := g.ValidEdit(param)
	if !b {
		return 0, errors.New(err)
	}
	group := Group{}
	group.Id, _ = strconv.Atoi(param["id"].(string))
	if param["group_name"] != nil {
		group.Group_name = param["group_name"].(string)
	}
	if param["status"] != nil {
		group.Status = param["status"].(int)
	}
	o := orm.NewOrm()
	return o.Update(&group)
}

//删除
func (m *GroupModels) Delete(id int) (int64, error) {
	o := orm.NewOrm()
	return o.Delete(&Group{Id: id})
}
